import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class BufferedImageExample {
    public static void main(String[] args) {
        try {
            // 创建一个空白的 BufferedImage
            int width = 200;
            int height = 200;
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

            // 获取 Graphics2D 对象以进行绘图操作
            Graphics2D g2d = image.createGraphics();

            // 设置背景色为白色
            g2d.setColor(java.awt.Color.WHITE);
            g2d.fillRect(0, 0, width, height);

            // 画一个红色的矩形
            g2d.setColor(java.awt.Color.RED);
            g2d.fillRect(50, 50, 100, 100);

            // 释放资源
            g2d.dispose();

            // 将图像保存到文件
            File outputfile = new File("saved.png");
            ImageIO.write(image, "png", outputfile);

            System.out.println("图像已成功保存到 saved.png");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}